import React from 'react'
import BaseComponent from 'basecomponent'
import icons from 'icons'
import Button from "button";
import './style.scss'
import AntTable from 'anttable'
import {Pagination} from 'antd';
import store from 'store'
import api from 'apis'
import {grideType, gradeType} from 'utils/staticType'
import {Cascader} from 'antd';
import UploadMusicModal from 'uploadMusicModal'
import moment from 'moment'
import appConfig from 'config'
import auth from 'auth'

const typeName = ['FirstTag', 'SecondTag', 'ThirdTag'];
class Major extends BaseComponent {
  constructor() {
    super(...arguments);
    const location = this.props.location;
    this.state = {
      majorData: {
        Id: location.query.Id ?  parseInt(location.query.Id) : 1,
        Name: '',
        Image: '',
        CommonMajor: {Id: -1},
        InstituteId: location.state ? location.state.cid : -1,
        CollegeId: location.state ? location.state.uid : -1,
        Introduce: '',
        Grade: -1,
        Timestamp: 0,
        Music: {
          Id: -1,
        }
      },
      from: location.state ? location.state.from : '',
      placeHolder: '',
      bachelorData: [], //本科
      juniorData: [], //专科
      masterData: [], //硕士
      isRevise: location.state.revise ? location.state.revise : false,
      page: 1,
      commentList: [],
      paginationCommentList: [],
      musicData: [{
        Id: '-',
        Name: '添加',
        PlayTimes:'-',
        Duration:'-',
        updateTime:'-'
      }],
      showModal:false
    }
    store.set('currentMId', location.query.Id ? location.query.Id : 1)
  }

  componentDidMount() {
    const {majorData} = this.state
    this.setState({from: this.props.location.state.from})
    if (!(majorData.Id === -1 || typeof majorData.Id === 'undefined')) {
      this.getMajorDetail(majorData.Id)
    }
    this.getMajorDictList(grideType.bachelor, true)
    this.getMajorDictList(grideType.junior, true)
    this.getMajorDictList(grideType.master, true)
  }

  getMajorDetail(mid) {
    const{musicData}=this.state
    let id = mid ? mid : store.get('CurrentMId');
    this.MDetailRP && this.MDetailRP.request.abort();
    this.MDetailRP = api.university.getMajorDetail(id);
    this.registerRequest(this.MDetailRP.request);
    this.MDetailRP.promise
      .then((res) => {
        let data = res.Data || []
        let holderName = ''
        if(data.CommonMajor){
          holderName = `${data.CommonMajor.FirstTag} / ${data.CommonMajor.SecondTag} / ${data.CommonMajor.ThirdTag}`
        }
        if(data.Music){
          musicData[0] = data.Music
          data.Music.Id && this.getCommentList(data.Music.Id)
        }
        this.setState({majorData: data, placeHolder: holderName , musicData:musicData});
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  getCommentList(id){
    this.CommentListRP && this.CommentListRP.request.abort();
    this.CommentListRP = api.music.getCommentList(id);
    this.registerRequest(this.CommentListRP.request);
    this.CommentListRP.promise
      .then((res)=>{
        let data = res.Data||[]
        this.setState({commentList: data, paginationCommentList: data.slice(0, 5)});
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  handleSubmit() {
    const {majorData} = this.state;
    if (!(majorData.Id === -1 || typeof majorData.Id === 'undefined')) {
      this.reviseMajorRP && this.reviseMajorRP.request.abort();
      console.log(majorData)
      this.reviseMajorRP = api.university.reviseMajor(majorData.Id, majorData);
      this.registerRequest(this.reviseMajorRP.request);
      this.reviseMajorRP.promise
        .then((res) => {
          res.Data && this.setState({majorData: res.Data},this.getMajorDetail(res.Data.Id));
          alert('修改成功')
        })
        .catch((err) => {
          alert(err.msg)
        })
    } else {
      this.addMajorRP && this.addMajorRP.request.abort();
      this.addMajorRP = api.university.addMajor(majorData);
      this.registerRequest(this.addMajorRP.request);
      this.addMajorRP.promise
        .then((res) => {
          res.Data && this.setState({majorData: res.Data},this.getMajorDetail(res.Data.Id));
          alert('添加成功')
        })
        .catch((err) => {
          alert(err.msg)
        })
    }
  }

  getMajorDictList(parent, init, targetParent, targetOption) {
    const {bachelorData, juniorData, masterData} = this.state
    if (!init) {
      this.majorDListRP.request.abort()
    }
    this.majorDListRP = api.majordict.getMajorDictList(parent);
    this.registerRequest(this.majorDListRP.request);
    this.majorDListRP.promise
      .then((res) => {
        let data = res.Data || [];
        if (init) {
          let optionData = data.map(function (item) {
            return {
              value: item.Id,
              label: item.FirstTag,
              origin: item,
              isLeaf: false,
            }
          })
          if (parent === grideType.bachelor) { //本科
            this.setState({bachelorData: optionData})
          }
          if (parent === grideType.junior) { //专科
            this.setState({juniorData: optionData})
          }
          if (parent === grideType.master) { // 硕士
            this.setState({masterData: optionData})
          }
        } else {
          if (targetOption) {
            let optionData = data.map(function (item) {
              return {
                value: item.Id.toString(),
                label: item[typeName[item.Type - 1]],
                origin: item,
                isLeaf: item.Type === typeName.length,
              }
            })
            targetOption.children = optionData
            if (targetParent === grideType.bachelor) {
              this.setState({bachelorData: [...bachelorData]})
            }
            if (targetParent === grideType.junior) { //专科
              this.setState({juniorData: [...juniorData]})
            }
            if (targetParent === grideType.master) { // 硕士
              this.setState({masterData: [...masterData]})
            }
          }
        }
      })
      .catch((err) => {
        alert(err.msg)
      })
  }

  handleLoadData(parent, selectedOptions) {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    this.getMajorDictList(targetOption.value, false, parent, targetOption)
  }

  onChange(value, selectedOptions) {
    const {majorData} = this.state
    if (selectedOptions && selectedOptions.length >= 1) {
      majorData.CommonMajor = {id: selectedOptions[selectedOptions.length - 1].origin.Id}
      console.log(majorData)
      this.setState({
        majorData: majorData
      })
    }
  }

  handlePaginationChange(page) {
    const {commentList} = this.state;
    this.setState({page: page, paginationCommentList: commentList.slice((page - 1) * 5, page * 5)})
  }

  handleMusicView(musicView) {
    const {musicData,majorData} = this.state
    if (majorData.CommonMajor) {
      delete majorData.CommonMajor
    }
    musicData[0].Id = musicView.Id
    musicData[0].Name = musicView.Name
    musicData[0].updateTime = moment(new Date()).format('YYYY.MM.DD hh:mm')
    let reviseMajor = Object.assign({},majorData,{Music:{Id:musicView.Id}})
    this.setState({musicData: musicData})
    this.RMajorRp && this.RMajorRp.request.abort();
    this.RMajorRp = api.university.reviseMajor(majorData.Id , reviseMajor);
    this.registerRequest(this.RMajorRp.request);
    this.RMajorRp.promise
      .then((res) => {
        res.Data&&this.setState({majorData:res.Data},this.getMajorDetail(res.Data.Id))
      })
      .catch((err)=>{
        alert(err.msg)
      })
  }

  render() {
    const {majorData, page, placeHolder, from, bachelorData, juniorData, masterData, commentList, paginationCommentList,showModal
    ,musicData} = this.state;
    const voiceColumns = [{
      title: '编号',
      dataIndex: 'Id',
      key: 'Id',
    }, {
      title: '专业名称',
      dataIndex: 'Name',
      key: 'Name',
    }, {
      title: '播放量',
      dataIndex: 'PlayTimes',
      key: 'PlayTimes',
    }, {
      title: '时长',
      dataIndex: 'Duration',
      key: 'Duration',
    }, {
      title: '上传时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
             <a onClick={() => {
               this.setState({showModal:true})
             }}>上传</a>
            <span className="ant-divider"/>
          <a href={`${appConfig.apiHost}/File/?pid=${text.Url}&key=${auth.getFileToken()}`}
             download={`${text.Name}.mp3`}>
            下载
          </a>
            <span className="ant-divider"/>
          <a onClick={() => {
            console.log('text',text)
          }}>删除</a>
        </span>
        ),
      }
    ];
    const voiceRowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
      }),
    };
    return (
      <div className={'sem-main-content'}>
        <div className={'major-button-wrapper'}>
          <Button className={'back-button'} onClick={() => {
            this.props.router.goBack()
          }}>{Button.AddOn({
            src: icons.backIcon, style: {
              width: '1rem',
              height: '1rem',
              display: 'block',
              backgroundRepeat: 'no-repeat',
            }
          })}</Button>
          <div className={'add-name'}>
            修改专业
          </div>
          <Button className={'save-btn'} onClick={this.handleSubmit.bind(this)}>保存</Button>
        </div>
        <div className={'major-top-div'}>
          <div className={'option-wrapper'}>
            <div className={'option-title'}>专业名称</div>
            <input className={'option-input'} type={'text'} value={majorData.Name}
                   onChange={(e) => {
                     this.setState({majorData: Object.assign(majorData, {Name: e.target.value})})
                   }}
            />
            <span className={'add-tool-div'}>
              <a onClick={() => {
                this.fixCompany(text, record)
              }}>修改</a>
                <span className="ant-divider"/>
              <a onClick={() => {
                this.watchCompany(text, record)
              }}>查看</a>
                <span className="ant-divider"/>
              <a onClick={() => {
                this.topCompany(text, record)
              }}>
                置顶
              </a>
              </span>
          </div>
        </div>

        {majorData.CommonMajor &&
        <div className={'add-select-div'}>
          <Cascader className={'level-select '}
                    size={'large'}
                    options={bachelorData}
                    loadData={this.handleLoadData.bind(this, grideType.bachelor)}
                    onChange={this.onChange.bind(this)}
                    placeholder={majorData.CommonMajor.Grade === gradeType.benke ? placeHolder : '本科专业'}
                    notFoundContent={'-'}>
          </Cascader>
          <Cascader className={'batch-select'}
                    size={'large'}
                    options={juniorData}
                    loadData={this.handleLoadData.bind(this, grideType.junior)}
                    onChange={this.onChange.bind(this)}
                    placeholder={majorData.CommonMajor.Grade === gradeType.zhuanke ? placeHolder : '专科专业'}
                    notFoundContent={'-'}>
          </Cascader>
          <Cascader className={'category-select'}
                    options={masterData}
                    loadData={this.handleLoadData.bind(this, grideType.master)}
                    onChange={this.onChange.bind(this)}
                    size={'large'}
                    placeholder={majorData.CommonMajor.Grade === gradeType.shuoshi ? placeHolder : '硕士专业'}
                    notFoundContent={'-'}>
          </Cascader>
        </div>
        }

        <div className={'major-middle-div'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>专业简介</span>
{/*            <Button className={'title-btn-save'} onClick={() => {
            }}>保存</Button>*/}
          </div>
          <textarea className={'work-intro'} value={majorData.Introduce}
                    onChange={(e) => {
                      this.setState({majorData: Object.assign(majorData,{Introduce: e.target.value})})
                    }}/>
        </div>

        <div className={'major-middle-div voice'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>专业视频</span>
          </div>
          <AntTable columns={voiceColumns} data={musicData} rowSelection={voiceRowSelection} pagenation={false}/>
        </div>

        <div className={'major-end-div'}>
          <div className={'title-wrapper'}>
            <span className={'title-bar'}/>
            <span className={'title-text'}>专业评论</span>
          </div>
          <ul className={'comment-ul'}>
            {
              paginationCommentList.map(function (item) {
                return <li className={'comment-li'} key={item.Id}>
                  <img className={'li-header'}  src={`${appConfig.apiHost}/File/?pid=${item.User.Image}&key=${auth.getFileToken()}`}/>
                  <div className={'li-body'}>
                    <span className={'nickname'}>{item.User.Name}</span>
                    <span className={'content'}>{item.Content}</span>
                  </div>
                  <span className={'li-time'}>{moment(new Date(item.UpdateTime)).format('YYYY-MM-DD HH:mm')}</span>
                </li>
              })
            }
          </ul>
          <Pagination defaultCurrent={page}
                      current={page}
                      pageSize={5}
                      total={commentList.length}
                      showTotal={(total, range) => `共${total}条记录，每页5条记录，当前显示第${page}页`}
                      onChange={this.handlePaginationChange.bind(this)}/>
        </div>
        {showModal && <UploadMusicModal handleSave={(musicView)=>{this.handleMusicView(musicView)}}
                                        hideModal={()=>{this.setState({showModal:false})}}/>}
      </div>
    );
  }
}

module.exports = Major;
